# -*- coding: utf-8 -*-

import random
from urllib.parse import unquote
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import json
import time
import os
import requests
import oss2
import sys
import io


def initialBrowser():
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    # 防止浏览器闪退
    # chrome_options.add_experimental_option("detach", True)

    # 通过pyautogui方法获得屏幕尺寸
    # driver_width, driver_height = pyautogui.size()
    # 设置浏览器窗口大小解决页面元素无法交互的问题
    chrome_options.add_argument('--window-size=%sx%s' % (1280, 720))

    browser = webdriver.Chrome(options=chrome_options)
    scan_url = "https://mp.weixin.qq.com/"
    browser.get(scan_url)
    # 无头浏览器模式下这个函数会失效
    # browser.maximize_window()

    return browser


# todo 获取cookie
def get_cookies(browser):
    # 这一步需要手动扫码
    time.sleep(20)
    cookies = browser.get_cookies()
    # 转成字符串
    dumps = json.dumps(cookies)
    with open("cookies.txt", "w") as f:
        f.write(dumps)
    #print("保存cookies文件成功")


def login(browser):
    with open("cookies.txt", "r", encoding="UTF-8") as f:
        # loads() 传的是json字符串，而 load() 传的是文件对象
        # 使用 loads() 时需要先读取文件在使用，而 load() 则不用
        cookies = json.loads(f.read())
        # 给浏览器添加cookies
    for cookie in cookies:
        # print(cookie)
        browser.add_cookie(cookie)
    # 刷新网页，cookies才会成功
    browser.refresh()


def get_url(browser):
    # 元素交互：点击私信 根据用户名获取图片的url地址
    time.sleep(0.1)
    sx_element = browser.find_element(By.XPATH, '//a[@title="私信"]')
    browser.get_screenshot_as_file("xxx.png")
    sx_element.click()
    time.sleep(0.1)
    # 从外部传入用户名参数（试了发现用户名获取不到）
    #xpath_str = '//a[text()="{}"]/../../../../../..//img'.format(username)
    xpath_str = '//div[@class="user-messages"]//img'
    #print(xpath_str)
    img_elements = browser.find_elements(By.XPATH, xpath_str)
    src_attr = img_elements[0].get_attribute("src")
    #print("图片路径:{}".format(src_attr))
    return src_attr


def get_file_name(url, headers):
    filename = ''
    if 'Content-Disposition' in headers and headers['Content-Disposition']:
        disposition_split = headers['Content-Disposition'].split(';')
        if len(disposition_split) > 1:
            if disposition_split[1].strip().lower().startswith('filename='):
                file_name = disposition_split[1].split('=')
                if len(file_name) > 1:
                    filename = unquote(file_name[1])
    if not filename and os.path.basename(url):
        filename = os.path.basename(url).split("?")[0]
    if not filename:
        return time.time()
    return filename


def generate_random_str(randomlength=6):
    """
    生成一个指定长度的随机字符串
    """
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    return random_str

# 设置print输出的编码格式
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
browser = initialBrowser()
# todo 判断文件存不存在，但是文件即使存在cookie也可能过期
exists = os.path.exists("cookies.txt")
if not exists:
    get_cookies(browser)
login(browser)
#username = sys.argv[1]
#print("username:{}".format(username))
url = get_url(browser)
# 获取cookies
cookies_1 = browser.get_cookies()
cookies = {}
for i in cookies_1:
    cookies[i["name"]] = i["value"]
#print(cookies)
# 这是保存到本地，实际上应该
# open('xxx.gif', 'wb').write(get_gif.content)
#print(url)
# 保存到oss
access_key = "LTAI5tPZcLuuuCpTfvJVVRzR"
access_key_secret = "dRa8GEdkQh2aJjDQDDYNwsJ9du9UXz"
# 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
auth = oss2.Auth(access_key, access_key_secret)
# yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
# 填写Bucket名称。
oss_end_point = "oss-cn-chengdu.aliyuncs.com"
bucket_name = "gulimall-ayu"
bucket = oss2.Bucket(auth, oss_end_point, bucket_name)
# requests.get返回的是一个可迭代对象（Iterable），此时Python SDK会通过Chunked Encoding方式上传。
# 填写网络流地址。
get_gif_input = requests.get(url, cookies=cookies)
# 文件大小
content_length = get_gif_input.headers['Content-Length']
# file_name = get_file_name(url, get_gif_input.headers)
# 填写Object完整路径。Object完整路径中不能包含Bucket名称。
# 文件名称
# "https://" + bucketName + "." + endpoint + "/" + 时间戳 + 随机字符串 + .gif
time_str = int(time.time())
#print("当前时间戳:{}".format(time_str))
random_str = generate_random_str()
# 默认传入当前时间
date1 = time.strftime('%Y-%m')
file_name = "{}/{}{}.gif".format(date1, time_str, random_str)
download_url = "https://{}.{}/{}".format(bucket_name, oss_end_point, file_name)
print(download_url)
bucket.put_object(file_name, get_gif_input)
